﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevComponents.DotNetBar;
using BookStore.Solution.BLL;
using BookStore.Solution.Entities;
using BookStore.Solution.Utilities;
using System.IO;
using BookStore.Solution.Configurations;

namespace BookStore.Solution.Presentation
{
    public partial class FrmBook : DevComponents.DotNetBar.OfficeForm
    {
        private bool addNew = true;
        List<Author> storeAuthor = new List<Author>();
        Product product;
        string result = "";
        public FrmBook()
        {
            InitializeComponent();
            LoadPubLisher();
            LoadCategory();
        }

        public FrmBook(string productID, bool viewdetail)
        {
            InitializeComponent();
            LoadPubLisher();
            LoadCategory();
            addNew = false;
            if (viewdetail)
            {
                txtProductID.Enabled = false;
                btnAddAuthor.Enabled = false;
                btnDelAuthor.Enabled = false;
                this.Text = "Xem chi tiết sách: " + productID;
                this.Height = Height - 40;
            }
            else
            {
                this.Text = "Cập nhật thông tin sách: " + productID;
                txtProductID.Enabled = false;
            }
            BookManager bookManager = new BookManager();
            Product product = new Product();
            product = bookManager.GetbyID(productID);
            txtProductID.Text = product.ProductID;
            txtProductName.Text = product.ProductName;
            //Nạp tác giả
            foreach (var a in product.Authors)
                grvAuthor.Rows.Add(a.AuthorID, a.AuthorName);
            txtYearPublication.Text = product.YearPublication.ToString();
            cbbCategory.SelectedValue = product.CategoryID;
            cbbPublisher.SelectedValue = product.PublisherID;
            txtPageNo.Text = product.PageNumber.ToString();
            txtVersion.Text = product.Version;
            txtQuantity.Text = product.Quatity.ToString();
            txtUnit.Text = product.Unit.ToString();
            txtUnitPrice.Text = product.UnitPrice.ToString();
            txtDescription.Text = product.Decription;
            if (product.Picture !=  "")
            {
                txtPath.Text = product.Picture;
                pbPicture.ImageLocation = product.Picture;
            }
            if(product.Status.Equals("Còn hàng")){
                rdAvaiable.Checked = true;
            }
            else if (product.Status.Equals("Hết hàng"))
            {
                rdUnvailable.Checked = true;
            }
            else
            {
                rdNoBusiness.Checked = true;
            }
        }

        private void LoadPubLisher()
        {
            PublisherManager publisher = new PublisherManager();
            cbbPublisher.DataSource = publisher.GetAll();
            cbbPublisher.DisplayMember = "PublisherName";
            cbbPublisher.ValueMember = "PublisherID";
        }

        private void LoadCategory()
        {
            CategoryManager category = new CategoryManager();
            cbbCategory.DataSource = category.GetAll("Sách");
            cbbCategory.DisplayMember = "CategoryName";
            cbbCategory.ValueMember = "CategoryID";
        }
        private void btnBrowse_Click(object sender, EventArgs e)
        {
            try
            {
                if (Ofd.ShowDialog() == DialogResult.OK)
                {
                    pbPicture.Image = Image.FromFile(Ofd.FileName);
                    txtPath.Text = Ofd.FileName.ToString();
                }
            }
            catch
            {
                pbPicture.Image = null;
            }
        }

        private void btnSubmit_Click(object sender, EventArgs e)
        {
            if (checkValidation())
            {
                CopyImage();
                product = new Product();
                AuthorManager authorManager = new AuthorManager();
                BookManager bookManager = new BookManager();
                Author author;
                product.ProductID = txtProductID.Text;
                product.ProductName = txtProductName.Text;
                for (int i = 0; i < grvAuthor.Rows.Count; i++)
                {
                    author = new Author();
                    author = authorManager.GetDetail(grvAuthor.Rows[i].Cells["AuthorID"].Value.ToString());
                    if (author != null)
                    {
                        product.Authors.Add(author);
                    }
                }
                try
                {
                    product.PublisherID = cbbPublisher.SelectedValue.ToString();
                }
                catch
                {
                    MessageBox.Show("Bạn chưa chọn nhà xuất bản!!!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                int yp = DataUtil.ToInt(txtYearPublication.Text, -1);
                if (yp == -1)
                    product.YearPublication = null;
                else
                    product.YearPublication = yp;
                product.Version = txtVersion.Text;
                try
                {
                    product.CategoryID = cbbCategory.SelectedValue.ToString();

                }
                catch
                {
                    MessageBox.Show("Bạn chưa chọn danh mục!!!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                if (txtPageNo.Text == "")
                    product.PageNumber = null;
                else
                    product.PageNumber = int.Parse(txtPageNo.Text);
                product.Decription = txtDescription.Text;
                product.Unit = txtUnit.Text;
                product.UnitPrice = long.Parse(txtUnitPrice.Text);
                product.Quatity = int.Parse(txtQuantity.Text);
                product.Picture = txtPath.Text;
                if (rdAvaiable.Checked)
                {
                    product.Status = "Còn hàng";
                }
                else if (rdUnvailable.Checked)
                {
                    product.Status = "Hết hàng";
                }
                else
                {
                    product.Status = "Không kinh doanh";
                }
                product.Type = "Sách";

                if (addNew)
                {
                    
                    result = bookManager.Insert(product);
                }
                else
                {
                    result = bookManager.Update(product);
                }
                MessageBox.Show(result, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show("Thêm không thành công, vui lòng kiểm tra lại các thông tin bị thiếu hoặc không đúng định dạng", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        private void CopyImage()
        {
            string new_dir = Configs.ImageFolderPath;
            string fileName = System.IO.Path.GetFileName(txtPath.Text);
            string fName = System.IO.Path.Combine(new_dir, fileName);
            if (!File.Exists(fName))
                System.IO.File.Copy(txtPath.Text, fName);
            txtPath.Text = fName;

        }
        private bool checkValidation()
        {
            if (txtProductID.Text == "")
            {
                lblProductID.ForeColor = Color.Red;
                return false;
            }
            if (txtProductName.Text == "")
            {
                lblProductName.ForeColor = Color.Red;
                return false;
            }
            int yp = DataUtil.ToInt(txtYearPublication.Text, -1);
            int pn = DataUtil.ToInt(txtPageNo.Text, -1);
            int quan = DataUtil.ToInt(txtQuantity.Text, -1);
            long price = DataUtil.ToLong(txtUnitPrice.Text,0);
            if(yp<=0){
                txtYearPublication.Text = "";
            }
            if (pn <= 0)
            {
                txtPageNo.Text = "";
            }
            if (quan <0)
            {
                this.lblQuantity.ForeColor = Color.Red;
                return false;
            }
            if (price == 0 || txtUnitPrice.Text == "")
            {
                this.lblUnitPrice.ForeColor = Color.Red;
                return false;
            }
            return true;
        }

        private void btnReset_Click(object sender, EventArgs e)
        {
            if (addNew == true)
                txtProductID.ResetText();
            txtProductName.ResetText();
            txtDescription.ResetText();
            txtPageNo.ResetText();
            txtPath.ResetText();
            txtQuantity.ResetText();
            txtUnit.ResetText();
            txtUnitPrice.ResetText();
            txtVersion.ResetText();
            txtYearPublication.ResetText();
            grvAuthor.Rows.Clear();
            pbPicture.Image = null;
        }

        private void btnAddAuthor_Click(object sender, EventArgs e)
        {
            bool isExist = false;
            for(int i = 0; i <grvAuthor.Rows.Count;i++)
            {
                if (grvAuthor.Rows[i].Cells["AuthorID"].Value.ToString().Equals(cbbAuthor.SelectedValue.ToString()))
                {
                    MessageBox.Show("Tác giả này đã có trong danh sách", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    isExist = true;
                    break;
                }
            }
            if (isExist == false)
                grvAuthor.Rows.Add(cbbAuthor.SelectedValue.ToString(), cbbAuthor.Text.ToString());
        }

        private void btnDelAuthor_Click(object sender, EventArgs e)
        {
            if (grvAuthor.SelectedRows.Count > 0)
            {
                //xóa dòng đầu tiên hay xóa tất cả các cái dã chọnđã chọn tất cả hả ừ. để ta thử
                for (int i = grvAuthor.SelectedRows.Count - 1; i >= 0; i--)
                    grvAuthor.Rows.RemoveAt(grvAuthor.SelectedRows[i].Index);
            }
            else
            {
                MessageBox.Show("Lựa chọn ít nhất 1 tác giả để xóa", "THông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void FrmBook_Load(object sender, EventArgs e)
        {
            //LoadPubLisher();
            //LoadCategory();
            AuthorManager authorManager = new AuthorManager();
            cbbAuthor.DataSource = authorManager.GetAll();
            cbbAuthor.DisplayMember = "AuthorName";
            cbbAuthor.ValueMember = "AuthorID";
        }

        private void btnDelPicture_Click(object sender, EventArgs e)
        {
            txtPath.Text = "";
            pbPicture.ResetText() ;
            pbPicture.Image = null;
        }
    }
}